package com.whwj.heaven.auth.service.impl;


import com.whwj.heaven.auth.constant.Constants;
import com.wjwh.heaven.common.core.exception.BadRequestException;
import com.wjwh.heaven.common.security.constant.SecurityConstant;
import com.wjwh.heaven.common.security.pojo.HeavenUserDto;
import com.wjwh.heaven.common.security.pojo.SecurityUser;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author: dm
 * @Date: 2020/3/29 11:07
 * @Description:
 */
@Service
@AllArgsConstructor
public class HeavenUserDetailsService implements UserDetailsService {


    private final HttpServletRequest request;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        HeavenUserDto userDto = findByUserDto(username);
        if (userDto==null) {
            throw new BadRequestException(HttpStatus.BAD_REQUEST, Constants.USERNAME_ERROR);
        }
        SecurityUser securityUser = new SecurityUser(userDto);
//        下沉到配置里边通过框架原有功能实现
//        if (!securityUser.isEnabled()) {
//            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
//        } else if (!securityUser.isAccountNonLocked()) {
//            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
//        } else if (!securityUser.isAccountNonExpired()) {
//            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
//        }
        if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(Constants.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

    /**
     * 根据标识查询用户信息
     * @param sign
     * @return
     */
    public HeavenUserDto findByUserDto(String sign){
        String clientId = request.getParameter("client_id");
        String password = "$2a$10$QpXFoz5fxDBUvl5bTonV8Oeb6924MXCXNRDGC6Ver3WCP4GnDCByW";
        if(SecurityConstant.ADMIN_CLIENT_ID.equals(clientId) || sign.equals("macro")){
            return new HeavenUserDto(1L,"macro", password,1, Arrays.asList("ADMIN"));
        }else if (sign.equals("andy")){
            return new HeavenUserDto(1111111L,"andy", password,1, Arrays.asList("TEST"));
        }
        return null;
    }


}
